<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 商户函数库
 * 
 * @desc 
 * @version 1.0.0 
 * @author  Jason
 * @date	2017年5月15日 下午3:17:19
 * 
 * @desc    继承基类
 * @version 1.1.0
 * @date	2017年6月12日 下午2:03:38
 */
class Lib_merchant extends Lib_database
{
	/** @var Mod_merchant */
	private $mod_merchant = null;
	
	/** @var Lib_language */
	private $lib_language = null;
	
	use libraries\common\LanguageCURD;
	
	use libraries\common\ConditionParser;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->CI->load->model('mod_merchant');
		$this->mod_merchant =& $this->CI->mod_merchant;
		
		$this->CI->load->library('lib_language');
		$this->lib_language =& $this->CI->lib_language;
		
		$this->set_render_config();
	}
	
	private function set_render_config()
	{
		$this->CI->load->model('mod_member');
		#$this->CI->load->model('mod_area'); MARK 地区是多语言的，这样做只适合默认语言
		$foreign_keys = [
				'master' => [
						['member_id', ['name'], $this->CI->mod_member, 'master', 'id'],
						['member_id', ['nickname'], $this->CI->mod_member, 'info', 'id'],
						['owner_id', ['name'], $this->CI->mod_member, 'master', 'id'],
						['owner_id', ['nickname'], $this->CI->mod_member, 'info', 'id'],
						#['country', ['name'], $this->CI->mod_area, 'master', 'id'],
						#['city', ['name'], $this->CI->mod_area, 'master', 'id'],
				],
		];
		$time_fields = [
				'master' => [
						['create_time', 'Y-m-d H:i:s'],
						['update_time', 'Y-m-d H:i:s'],
				],
		];
		$encode_fields = [
				'master' => [
						['images', 'implode'],			// 多图图片
						['license', 'implode'],			// 多图图片
				],
		];
		$this->foreign_keys = $foreign_keys;
		$this->time_fields = $time_fields;
		$this->encode_fields = $encode_fields;
	}
	
	public function get_merchants_as_poi($country, $city, $language)
	{
		$list = $this->mod_merchant->get_as_poi_by_country_city($country, $city);
		
		$module = $this->mod_merchant->get_multi_language_info('module');
		$field_names = 'name';
		$list = $this->lib_language->get_merged_list_data_with_fields($list, $module, $language, $field_names);
		
		return $list;
	}
	
	public function get_ids_for_autocomplete($country, $city)
	{
		$array = $this->mod_merchant->get_ids_by_country_city($country, $city);
		
		// TO DO maybe a func for liblang
		// Lib_language::get_list_for_search_in_multi_module($keyword, $module_resources_pairs, $language, $by_fields = ['name']);
		
		return $array;
	}
	
	public function get_merchant_for_detail($id, $language)
	{
		$module = $this->mod_merchant->get_multi_language_info('module', 'master');
		$merchant = $this->mod_merchant->select_instance_by_id($id);
		if (empty($merchant)) {
			return $merchant;
		}
		$merchant = $this->lib_language->get_merged_item_data($merchant, $module, $language);
		$merchant = $this->render_list($merchant, 'master', true, [
				[$this, 'parse_item_status'],
		]);
		
		$merchant['direction_url'] = sprintf("https://www.google.com/maps/dir/current+location/%s,%s", $merchant['latitude'], $merchant['longitude']);
		
		$module = 'area';
		$resources = array($merchant['country'], $merchant['city']);
		$merchant['address_string'] = sprintf('%s %s %s',
				$this->lib_language->get_concat_values_string_by_language($module, $resources, $language),
				$merchant['street'],
				$merchant['address']
		);
		
		return $merchant;
	}
	
	/**
	 * 获取供简单列表使用的商户列表信息(一般前台用)
	 *
	 * @param array  $conditions
	 * @param string $language
	 * @param number $page
	 * @param number $number
	 * @param array $status_tags
	 */
	public function get_merchants_for_list($conditions, $language, $page = 1, $number = 12, $status_tags = ['enabled'])
	{
		$conditions[] = ['select', 'id,cover,name,abstract,summary,mobile,email,website,country,city,street,address,latitude,longitude,zipcode,is_official,score_average'];
		if (!empty($status_tags)) {
			$where =  $this->mod_merchant->calculate_status_condition_where($status_tags);
			$conditions[] = ['where', $where];
		}
		
		$result = $this->mod_merchant->get_list($conditions, $page, $number);
		foreach ($result['data'] as &$merchant){
			$merchant['direction_url'] = sprintf("https://www.google.com/maps/dir/current+location/%s,%s", $merchant['latitude'], $merchant['longitude']);
				
			$module = 'area';
			$resources = array($merchant['country'], $merchant['city']);
			$merchant['address_string'] = sprintf('%s %s %s',
					$this->lib_language->get_concat_values_string_by_language($module, $resources, $language),
					$merchant['street'],
					$merchant['address']
					);
		}
		
		$module = $this->mod_merchant->get_multi_language_info('module');
		$field_names = ['name', 'abstract', 'summary'];
		$result['data'] = $this->lib_language->get_merged_list_data_with_fields($result['data'], $module, $language, $field_names);
		
		return $result;
	}
	
	/**
	 * 获取供管理员使用的商户列表信息(一般后台用)
	 *
	 * @param array  $conditions
	 * @param string $language
	 * @param number $page
	 * @param number $number
	 */
	public function get_merchants_for_manage_list($conditions, $language, $page = 1, $number = 12)
	{
		$conditions[] = ['select', 'id,cover,images,license,name,mobile,email,website,country,city,street,address,zipcode,is_official,create_time,update_time,member_id,owner_id,status'];
		
		$result = $this->mod_merchant->get_list($conditions, $page, $number);
		$result['data'] = $this->render_list($result['data'], 'master', false, [
				[$this, 'parse_item_status'],
		]);
		
		$module = $this->mod_merchant->get_multi_language_info('module');
		$field_names = ['name'];
		$result['data'] = $this->lib_language->get_merged_list_data_with_fields($result['data'], $module, $language, $field_names);
		
		foreach ($result['data'] as &$item) {
			$module = 'area';
			$resources = array($item['country'], $item['city']);
			$item['address_string'] = sprintf('%s %s %s',
					$this->lib_language->get_concat_values_string_by_language($module, $resources, $language),
					@$item['street'],
					@$item['address']
			);
		}
		
		return $result;
	}
	
	public function parse_item_status($item)
	{
		$item['status_tags'] = $this->mod_merchant->calculate_status_tags($item['status']);
		$item['status_tags'] = $this->filter_checking_status($item['status_tags']);
		return $item;
	}
	
	/**
	 * 获取商户信息做为抬头
	 * 
	 * @desc    获取商户信息，做为路线等的子表外键的抬头
	 * @author  Jason
	 * @date    2017年5月17日 下午5:12:06
	 * 
	 * @param   number $id 
	 * @param   string $language 
	 * 
	 * @return  array
	 */
	public function get_merchant_as_title($id, $language)
	{
		$module = $this->mod_merchant->get_multi_language_info('module', 'master');
		$this->CI->db->select('id,cover,name,abstract,mobile,email,website,latitude,longitude,is_official,zipcode,country,city,street,address');
		$merchant = $this->mod_merchant->select_instance_by_id($id);
		#print_r($merchant);exit;
		
		$module = $this->mod_merchant->get_multi_language_info('module');
		$field_names = ['name','abstract'];
		$merchant = $this->lib_language->get_merged_item_data_with_fields($merchant, $module, $language, $field_names);
		
		$merchant['direction_url'] = sprintf("https://www.google.com/maps/dir/current+location/%s,%s", $merchant['latitude'], $merchant['longitude']);
		
		$module = 'area';
		$resources = array($merchant['country'], $merchant['city']);
		$merchant['address_string'] = sprintf('%s %s %s',
				$this->lib_language->get_concat_values_string_by_language($module, $resources, $language),
				$merchant['street'],
				$merchant['address']
		);
		
		return $merchant;
	}
	
	public function get_merchant_as_key_by_owner($owner_id)
	{
		$conditions = [
				['select', 'id,owner_id,status'],
				['where', "owner_id=$owner_id"],
		];
		$merchant = $this->mod_merchant->select_instances_by_conditions($conditions);
		$merchant = array_shift($merchant);
		
		return $merchant;
	}
	
	public function create_merchant_for_business($owner_id)
	{
		$data = [
				'member_id' => $owner_id,
				'owner_id' => $owner_id,
				'status' => '1', // 让它默认启用，但待审核即可
		];
		list($status, $newData) = $this->mod_merchant->create_instance($data);
		
		return $newData;
	}
	
	/**
	 * 名字这么长，这样好么？
	 * 
	 * @param unknown $owner_id
	 */
	public function create_or_get_merchant_as_key_for_business_by_owner($owner_id)
	{
		$merchant = $this->get_merchant_as_key_by_owner($owner_id);// null or array
		if (empty($merchant)) {
			$merchant = $this->create_merchant_for_business($owner_id);// array
		}
		return $merchant;
	}
	
	/**
	 * 追加商户表指定字段信息
	 *
	 * @desc    仅添加主表非多语言字段，首参直接传引用
	 * @author  Jason
	 * @date	2017年5月18日 下午4:00:19
	 *
	 * @param   array $list		路线列表，或者带 merchant_id 字体的列表
	 * @param   array $fields	要追加的商户字段
	 * 
	 * @return  null
	 */
	public function append_merchant_official(&$list, $fields = ['is_official'])
	{
		$ids = array_column($list, 'merchant_id');
		$ids[] = -1;
		
		$fields[] = 'id';
		$select = implode(',', $fields);
		$conditions[] = ['select', $select];
		$conditions[] = ['where_in', ['id', $ids]];
		
		$merchants = $this->mod_merchant->select_instances_by_conditions($conditions);
		$merchants = array_column($merchants, null, 'id');
		foreach ($list as $key => &$item) {
			if (empty($merchants[$item['merchant_id']])) {
				$merchants[$item['merchant_id']] = array_fill_keys($fields, null);
			}
			unset($merchants[$item['merchant_id']]['id']);
			$item = array_merge($item, $merchants[$item['merchant_id']]);
		}
		unset($item);
		// print_r($list);exit;
	}
	
	public function check_status($merchant_id)
	{
		$status = $this->mod_merchant->select_fields_by_id($merchant_id, 'status');
		$tags = $this->mod_merchant->calculate_status_tags($status, 'negative');
		
		$status = true;
		$content = [];
		if(in_array('check_doing', $tags) || in_array('unchecked', $tags) || in_array('disabled', $tags)) {
			$status = false;
			$content = array_map(function($value) {
				return "merchant_msg_merchant_status_$value";
			}, $tags);
		}
		return [$status, $content];
	}
	
	
	/**
	 * 商户启用禁用
	 *
	 * @author  Jason
	 * @date	2017年6月14日 下午2:31:25
	 *
	 * @param number $id
	 *
	 * @return [<status>, <content>]	一个两元素数组，第一个元素表示状态，第二个表示相应内容
	 * 	        eg:	[true, ['nowTag' => 'enabled']]
	 * 				[true, ['nowTag' => 'disabled']]
	 * 				[false, ['error']]
	 */
	public function toggle_status_enabled($id)
	{
		$status = true;
		$ultimateTag = $this->mod_merchant->toggle_status_by_tag($id);
		
		return [$status, ['nowTag' => $ultimateTag]];
	}
	/**
	 * 商户审核通过与不通过
	 * 
	 * @author  Jason
	 * @date	2017年6月14日 下午3:42:02
	 *
	 * @param number $id
	 *
	 * @return [<status>, <content>]	一个两元素数组，第一个元素表示状态，第二个表示相应内容
	 * 	        eg:	[true, ['nowTag' => 'enabled']]
	 * 				[true, ['nowTag' => 'disabled']]
	 * 				[false, ['error']]
	 */
	public function toggle_status_checked($id)
	{
		$status = true;
		$ultimateTag = $this->mod_merchant->toggle_status_by_tag($id, 'checked');
	
		return [$status, ['nowTag' => $ultimateTag]];
	}
	
	/**
	 * 状态之审核：审核通过和未通过
	 * 
	 * @desc    审核通过和未通过
	 * @author  Jason
	 * @date	2017年6月20日 上午11:31:11
	 * 
	 * @param   number $id			ID
	 * @param   string $judgement	通过还是不通过，accepted/rejected，默认拒绝
	 * @param   string $comment		通过备注，不通过原因
	 * @param   string $module		模块名称，要审核的数据模型名称
	 * 
	 * @return [<status>, <content>]	一个两元素数组，第一个元素表示状态，第二个表示相应内容
	 * 	        eg:	[true, ['nowTag' => 'enabled']]
	 * 				[true, ['nowTag' => 'disabled']]
	 * 				[false, ['error']]
	 */
	use libraries\common\CheckingStatus;
	
	
	public function need_complete_info($merchant)
	{
		if (!isset($merchant['status'])) {
			return false;
		}
		
// 		$merchant = $this->CI->session->MY_MERCHANT;
		$status_tags = $this->mod_merchant->calculate_status_tags($merchant['status'], 'negative');
		if (in_array('check_doing', $status_tags)) {
			return false;
		} else if (in_array('checked', $status_tags)) {
			return false;
		}
		
		return true;
	}
	
// 	public function __call($name, $arguments)
// 	{
// 		if (method_exists($this->mod_merchant, $name)) {
// 			$callback = [$this->mod_merchant, $name];
// 			return call_user_func_array($callback, $arguments);
// 		}
		
// 		throw new Exception('No Such method');
// 	}
	
	public function cumulative_score($id, $score)
	{
		$score = floatval($score);
		$this->mod_merchant->db->set('score_average', "( `score_average` * `score_count` + $score ) / ( `score_count` + 1 )", false);
		$this->mod_merchant->db->set('score_count', "`score_count` + 1", false);
		$this->mod_merchant->db->where('id', $id);
		$this->mod_merchant->db->update('merchant');
	}
}